package com.leo.springbootmultithreadbasic.java8;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author Leo
 * @version V1.0
 */
public class CompletableFutureDemo {

    private static final Logger logger = LoggerFactory.getLogger(CompletableFutureDemo.class);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test();
    }

    /**
     * 模拟 RPC 回调
     */
    public static void test() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(CompletableFutureDemo::callRpc1);

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(CompletableFutureDemo::callRpc2);

        CompletableFuture<String> future3 = future1.thenCombine(future2, (out1,out2) -> {return out1 + "&" +  out2;});

        logger.info("合并的结果：{}", future3.get());
    }

    public static String callRpc1() {
        // 模拟业务处理耗时
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.debug("rpc call 1");
        return "rpc call 1";
    }

    public static String callRpc2() {
        // 模拟业务处理耗时
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.debug("rpc call 2");
        return "rpc call 2";
    }
}
